import { ActionContext } from 'vuex';
import zhCN from 'ant-design-vue/es/locale/zh_CN';
import enUS from 'ant-design-vue/es/locale/en_US';
import { ResponseHandle } from '@/global/util/preUtils';
import { login, logout, register, getUserInfo } from '@/core/api';
interface State {
  themeType: string;
  language: string;
  dragDomData: { [key: string]: any };
  userInfo: { [key: string]: any };
}

const getAntdLocale = (type: string) => {
  switch (type) {
    case 'en-us':
      return enUS;
    case 'zh-en':
      return zhCN;
    default:
      return zhCN;
  }
};

const state: State = {
  themeType: localStorage.getItem('themeType') || 'peacockGreen',
  language: localStorage.getItem('language') || 'zh-en',
  dragDomData: {},
  userInfo: {},
};
const getters = {
  locale: (state: State) => getAntdLocale(state.language),
};
const actions = {
  async login(context: ActionContext<State, any>, params: any) {
    const res: any = await login(params);
    ResponseHandle(res, () => {
      context.commit('SetUserInfo', res.data);
      const { protocol, host, pathname } = window.location;
      window.location.href = `${protocol}//${host}${pathname}#/`;
    });
  },
  async logout(context: ActionContext<State, any>) {
    const res: any = await logout();
    ResponseHandle(res, () => {
      const { protocol, host, pathname } = window.location;
      window.location.href = `${protocol}//${host}${pathname}#/login`;
    });
  },
  async register(context: ActionContext<State, any>, params: any) {
    const res: any = await register(params);
    return res;
  },
  async getUserInfo(context: ActionContext<State, any>, params: any) {
    const res: any = await getUserInfo(params);
    ResponseHandle(res, () => {
      context.commit('SetUserInfo', res.data);
    });
    return res;
  },
};
const mutations = {
  SetUserInfo(state: State, data: any) {
    state.userInfo = data;
  },
  SetThemeType(state: State, data: string) {
    state.themeType = data;
  },
  SetLocale(state: State, data: string) {
    state.language = data;
  },
  SetDragDomData(state: State, data: any) {
    state.dragDomData = data;
  },
};
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
